package com.chinaway.mobile.authcode;


import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chinaway.mobile.authcode.util.Filter;
import com.chinaway.mobile.authcode.util.Tools;

public class AuthCodeDiscernSdimpl implements AuthCodeDiscern{
	private static final Log log = LogFactory.getLog(AuthCodeDiscernSdimpl.class);
	private  String sdDownImagePath ="checkImg/" ; 
	
	@Override
	public String discern(BufferedImage image,boolean print) {
		
			Filter.filterBlack(image) ;
			if(print){
				String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
				Tools.writeImageToFile(sdDownImagePath+name + ".jpg", image);
			}
			BufferedImage[] arrayImg= Tools.getSdCheckCodes(image) ;
			Map<BufferedImage, String> map = null;
			try {
				map = Tools.loadTrainData("sd");
			} catch (Exception e) {
				log.error("", e);
			}
			String result = "";
			for (BufferedImage img : arrayImg) {
				result += Tools.getSingleCharOcr(img, map);
			}
			return filterString(result);
		 
	}
	private  String filterString(String str){
		str = StringUtils.trimToNull(str) ;
		StringBuffer sb = new StringBuffer();
        String regEx = "[0-9]" ; 
        Pattern p = Pattern.compile(regEx);
        String[] array_s = str.split("");
        for(String s:array_s){
        	Matcher m = p.matcher(s);   
	        if(m.find()){
	        	sb.append(s) ;
	        }
        }
        String s = sb.toString() ;
        if(StringUtils.isNotBlank(s)){
        	if(s.length()!= 4){
        		 s= "" ;
        	}
        }
        return s ;
	}
	public void setSdDownImagePath(String sdDownImagePath) {
		this.sdDownImagePath = sdDownImagePath;
	}
	 
}
